<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <search ref="search"  :config="searchConfig" @search="search" @getHeight="getHeight"/>
    <!-- table区域-begin -->
    <div>
      <vxe-grid
        ref='xGrid'
        :border='true'
        :resizable='true'
        :showOverflow='true'
        size='mini'
        :loading='loading'
        :height='pageHeight-seachHeight-94'
        :align='left'
        :columns='columns'
        :data='dataSource'
        :toolbar-config="tableToolbar"
       :checkbox-config="checkboxConfig"
        v-bind='vexConfig'
        @checkbox-change='selectChangeEvent'
        @checkbox-all="selectChangeEvent"
      >

        <template #toolbar_buttons>
          <div class='table-operator'>
            <a-button v-has="'vehicleConfiguration:add'" @click='handleAdd'>新增</a-button>
            <a-button v-has="'vehicleConfiguration:delete'" @click='batchDel'>删除</a-button>
            <a-button v-has="'vehicleConfiguration:synchronization'"  @click=''>同步</a-button>
            <a-button v-has="'vehicleConfiguration:export'"  @click=''>导出</a-button>
<!--            <a-button type='primary' :disabled='selectionRows.length!==1' v-has="'business:log'" @click='handleBusiness'>日志</a-button>-->
          </div>
        </template>

        <template #updateStatus='{ row,rowIndex }'>
          <a-switch :checked="row.status==1" size="small" :value="row"  @change="changeStatus($event,row)" />
        </template>
        <template #detail='{ row,rowIndex }'>
          <a style="color: #1890FF" @click="handleAdd(row,'详情',true,true)">{{row.pupCode}}</a>
        </template>
        <template #action='{ row,rowIndex }'>
          <a v-has="'vehicleConfiguration:update'" @click="handleAdd(row,'编辑')">编辑</a>
          <a-divider type='vertical'  />
          <a v-has="'business:log'" href='javascript:' @click='handleBusiness("车型配置",row)'>日志</a>
        </template>
        <template #pager>
          <vxe-pager
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :currentPage.sync='ipagination.current'
            :page-size.sync='ipagination.pageSize'
            :total='ipagination.total'
            :pageSizes='ipagination.pageSizeOptions'
            @page-change='handlePageChange'>
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <!-- table区域-end -->
    <!-- 表单区域 -->
    <business-log ref='businessLog'></business-log>
    <form-add-edit ref='popupForm' @ok='loadData'></form-add-edit>

  </a-card>
</template>

<script>

import JSuperQuery from '@/components/cn-form/JSuperQuery.vue'
import JInput from '@/components/cn-form/JInput.vue'
import { PageListMixin } from '@/mixins/PageListMixin'
import Vue from 'vue'
import { filterObj } from '@/utils/util'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import { postAction } from '../../../api/manage'
import { getAction } from '@/api/manage'
import search from '@comp/view/base-crud/search/Search'
import FormAddEdit from '@comp/view/base-crud/form/FormAddEdit'
//高级查询modal需要参数

export default {
  name: 'material',
  mixins: [PageListMixin],
  components: {
    JSuperQuery,
    FormAddEdit,
    JInput,
    JTreeSelect,
    search
  },
  // priceAdd
  data() {
    return {
      description: '经销商可购清单',
      //字典数组缓存
      sexDictOptions: [],
      importExcelUrl: `${window._CONFIG['domianURL']}/test/cn-formDemo/importExcel`,
      searchConfig: [
        {
          // label:'订单编号',
          type: 'input',
          name: 'pupCode',
          placeholder: '提货点编号'
        },
        {
          type: 'input',
          name: 'pupName',
          placeholder: '提货点名称'
        },
        {
          type: 'input',
          name: 'modelName',
          placeholder: '车型'
        },
        {
          type: 'a-select',
          name: 'status',
          option: [{
            name: '启用',
            value: '1'
          }, {
            name: '停用',
            value: 0
          }],
          placeholder: '请选择状态'
        }],
      //表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义  表格改这儿
      defColumns: [
        { type: 'checkbox', width: 60, fixed: 'left' },

        {
          title: '提货点编号',
          align: 'center',
          field: 'pupCode',
          fixed: 'left',
          minWidth: 80,
          slots: { default: 'detail' }
        },
        {
          title: '提货名称',
          align: 'center',
          field: 'pupName',
          minWidth: 80
        },
        {
          title: '销售组织名称',
          align: 'center',
          field: 'companyName',
          minWidth: 100
        },
        {
          title: '经销商等级',
          align: 'center',
          field: 'customerLevel',
          minWidth: 80
        },
        {
          title: '经销商编号',
          align: 'center',
          field: 'customerCode',
          minWidth: 80
        },
        {
          title: '经销商名称',
          align: 'center',
          field: 'customerName',
          minWidth: 80
        },
        {
          title: '车型',
          align: 'center',
          field: 'modelName',
          minWidth: 80
        },
        {
          title: '最小里程',
          align: 'center',
          field: 'minMileage',
          minWidth: 80
        },
        {
          title: '最大里程',
          align: 'center',
          field: 'maxMileage',
          minWidth: 80
        },

        {
          title: '最小运载',
          align: 'center',
          field: 'minCarry',
          minWidth: 80
        },
        {
          title: '最大运载',
          align: 'center',
          field: 'maxCarry',
          minWidth: 80
        },
        {
          title: '最大载重',
          align: 'center',
          field: 'maxLoad',
          minWidth: 80
        },
        {
          title: '备注',
          align: 'center',
          field: 'remarks',
          minWidth: 80
        },
        {
          title: '创建人',
          align: 'center',
          field: 'createName',
          minWidth: 80
        },
        {
          title: '创建时间',
          align: 'center',
          field: 'createTime',
          minWidth: 80
        },
        {
          title: '更新人',
          align: 'center',
          field: 'updateName',
          minWidth: 80
        },
        {
          title: '更新时间',
          align: 'center',
          field: 'updateTime',
          minWidth: 80
        },
        {
          title: '状态',
          align: 'center',
          field: 'status',
          fixed: 'right',
          minWidth: 80,
          slots: {
            default: 'updateStatus'
          }
        },
        {
          title: '操作',
          field: 'action',
          fixed: 'right',
          align: 'center',
          minWidth: 120,
          slots: {
            default: 'action'
          }
        }
      ],
      url: {
        list: window._CONFIG['domianURL'] + '/modelconfig/cnModelConfig/findPageList',
        detail: window._CONFIG['domianURL'] + '/material/getInfo',
        delete: window._CONFIG['domianURL'] + '/modelconfig/cnModelConfig/delete',
        startOrStopUrl: window._CONFIG['domianURL'] + '/modelconfig/cnModelConfig/startOrStop',
        deleteBatch: '/modelconfig/cnModelConfig/deleteBatch',
        exportXlsUrl: '/test/cn-formDemo/exportXls'

      }

    }
  },
  methods: {
    startorstop: function(status) {
      if (!this.url.startOrStopUrl) {
        this.$message.error('请设置url启用停用!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')

      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认修改',
          content: '是否修改选中数据?',
          onOk: function() {
            that.loading = true
            getAction(that.url.startOrStopUrl, { ids: ids, status: status }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })
      }
    },
    handleAdd(record = {}, title = '新增', disabled = false, disableSubmit = false) {
      // let newDate = formatDateYmd(new Date().getTime())
      // ...this.selectionRows, startDate: newDate, endDate: newDate
      let config = {
        title: title,
        width: 800,
        addOrUpdateUrl: `/modelconfig/cnModelConfig/saveOrUpdate`,  //审核地址
        method: 'post',
        list: [
          {
            label: '提货点编号',
            type: 'input-search',
            name: 'pupCode',  // 后台接受字段
            code: 'pupName',
            placeholder: '提货点编号',
            md: 12,
            disabled: disabled,
            status:'Pickuppoint',
            formconfig : [
              {
                key: 'pupCode',
                label: '提货点编号'
              },
              {
                key: 'goodsName',
                label: '提货点名称'
              }
            ],
            tableconfig:{
              columns: [
                {
                  title: '提货点编号',
                  align: 'center',
                  dataIndex: 'pupCode',
                  width: 120,
                  ellipsis: true
                },
                {
                  title: '提货点名称',
                  align: 'center',
                  dataIndex: 'pupName',
                  width: 120,
                  ellipsis: true
                }
              ],
              list: window._CONFIG['domianURL'] + '/pupconfig/cnPupConfig/findPageList',
              multiple: false,
              columW: 8,
              name:'提货点'
            }
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '提货点名称',
            type: 'input',
            placeholder: '提货点名称',
            disabled: true,
            name: 'pupName',  // 后台接受字段
            md: 12
            // check: { rules: [{ required: true, message: '代码生成表对象集合',whitespace:true }] }
          },
          {
            label: '销售组织',
            type: 'input',
            name: 'companyName',  // 后台接受字段
            placeholder: '',
            dictCode: '',
            disabled:disabled,
            md: 12
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '车型',
            type: 'input',
            name: 'modelName',  // 后台接受字段
            placeholder: '',
            dictCode: '',
            disabled:disabled,
            md: 12
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '经销商编号',
            type: 'input',
            name: 'customerCode',  // 后台接受字段
            placeholder: '',
            dictCode: '',
            disabled:disabled,
            md: 12
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '经销商名称',
            type: 'input',
            name: 'customerName',  // 后台接受字段
            placeholder: '',
            dictCode: '',
            disabled:disabled,
            md: 12
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '经销商等级',
            type: 'input',
            name: 'customerLevel',  // 后台接受字段
            placeholder: '',
            dictCode: '',
            disabled:disabled,
            md: 12
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '最大运载',
            type: 'input-number',
            name: 'maxCarry',  // 后台接受字段
            placeholder: '',
            min:'0',
            dictCode: '',
            disabled:disabled,
            md: 12
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '最小运载',
            type: 'input-number',
            name: 'minCarry',  // 后台接受字段
            placeholder: '',
            min:'0',
            dictCode: '',
            disabled:disabled,
            md: 12
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },


          {
            label: '最大里程',
            type: 'input-number',
            name: 'maxMileage',  // 后台接受字段
            placeholder: '',
            dictCode: '',
            min:'0',
            disabled:disabled,
            md: 12
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '最小里程',
            type: 'input-number',
            name: 'minMileage',  // 后台接受字段
            placeholder: '',
            min:'0',
            dictCode: '',
            disabled:disabled,
            md: 12
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '最大载重（kg）',
            type: 'input-number',
            name: 'maxLoad',  // 后台接受字段
            placeholder: '',
            min:'0',
            dictCode: '',
            disabled:disabled,
            md: 12
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '备注',
            type: 'textarea',
            placeholder: '',
            disabled:disabled,
            md: 12,
            // labelCol: {
            //   xs: { span: 28 },
            //   sm: { span: 3 }
            // },
            name: 'remarks'  // 后台接受字段
          }
        ]

      }
      this.$refs.popupForm.edit(record, config)
      this.$refs.popupForm.disableSubmit = disableSubmit

    },
    startorstopByid(status, id) {
      let that = this
      that.loading = true
      getAction(that.url.startOrStopUrl, { ids: id, status: status }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
          that.onClearSelected()
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        that.loading = false
      })
    },
    changeStatus(e, item) {
      if (e) {
        this.startorstopByid(1, item.id)
      } else {
        this.startorstopByid(0, item.id)
      }
    },
    handleEdit: async function(row) {
      // let option=[]
      // let res = await getAction(window._CONFIG['domianConfigURL'] + '/genDataConfigController/getInfo',{id:row.id})
      // if(res.success){
      //   option = res.result.map(item=>{
      //     return {
      //       name:item.name,
      //       value:item.code
      //     }
      //   })
      // }else {
      //   this.$message.error(res.message)
      // }

      // let newDate = formatDateYmd(new Date().getTime())
      // ...this.selectionRows, startDate: newDate, endDate: newDate
      this.$refs.popupForm.edit(row, this.config)
      this.$refs.popupForm.disableSubmit = false
    },
    selectCusttype(value) {
      this.$set(this.queryParam, 'custType', value)
    },


    getQueryParams() {
      //高级查询器
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)

      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      delete param.birthdayRange //范围参数不传递后台
      return filterObj(param)
    },
    // initDictConfig() {
    //   console.log("--我才是真的方法!--")
    //初始化字典 - 性别
    // initDictOptions('sex').then((res) => {
    //   if (res.success) {
    //     this.sexDictOptions = res.result;
    //   }
    // });
    // },
    onBirthdayChange: function(value, dateString) {
      console.log(dateString[0], dateString[1])
      this.queryParam.birthday_begin = dateString[0]
      this.queryParam.birthday_end = dateString[1]
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.field == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.field)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function(item, i, array) {
          allSettingColumns.push(item.field)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.field == 'action') {
            return true
          }
          if (colSettings.includes(item.field)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    }
  },
  created() {
    this.initColumns()
  }

}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>